import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/storage'
const Login = () => import('@/views/Login')
const Layout = () => import('@/views/Layout')
const Home = () => import('@/views/Layout/Home')
const Articles = () => import('@/views/Layout/Articles')
const Pictures = () => import('@/views/Layout/Pictures')
const Comments = () => import('@/views/Layout/Comments')
const Settings = () => import('@/views/Layout/Settings')
const Fans = () => import('@/views/Layout/Fans')
const NotFound = () => import('@/views/NotFound')
const AddArticle = () => import('@/views/Layout/Articles/add')
const EditArticle = () => import('@/views/Layout/Articles/edit')

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '/',
        component: Home
      },
      {
        path: '/articles',
        component: Articles
      },
      {
        path: '/pictures',
        component: Pictures
      },
      {
        path: '/add-article',
        component: AddArticle
      },
      {
        path: '/edit-article/:id',
        component: EditArticle
      },
      {
        path: '/comments',
        component: Comments
      },
      {
        path: '/fans',
        component: Fans
      },
      {
        path: '/settings',
        component: Settings
      }
    ]
  },
  {
    // * 表示匹配所有路径  用于放最后配置404
    path: '*',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})

// 配置路由的导航守卫
// beforeEach提供的函数会在所有的路由发生跳转之前
// next() 如果直接调用next() 代表放行 next('/login') 代表跳转到login
// 1. 如果有token 或者去登录  就直接放行
// 2. 否则就拦截到导航去
router.beforeEach((to, from, next) => {
  const token = getToken()
  if (to.path === '/login' || token) {
    next()
  } else {
    next('/login')
  }
})

export default router
